package net.suncaper.mvc.web.filter;

import net.suncaper.mvc.common.utils.JSONUtil;
import net.suncaper.mvc.common.utils.Result;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 认证过滤器，用于拦截未登录用户的请求
 */
public class AuthenticationFilter implements Filter {
    
    // 不需要登录即可访问的路径
    private final List<String> excludedPaths = Arrays.asList(
            "/api/user/login.do",
            "/api/user/create.do",
            "/api/hotel/listByLocation.do",
            "/api/hotel/get.do"
    );
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 设置跨域响应头
        httpResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");

        // 处理预检请求（OPTIONS），直接返回
        if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        String requestPath = httpRequest.getServletPath();

        // 如果是不需要登录的路径，直接放行
        if (isExcludedPath(requestPath)) {
            chain.doFilter(request, response);
            return;
        }

        // 检查用户是否已登录
        HttpSession session = httpRequest.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            // 用户已登录，放行
            chain.doFilter(request, response);
        } else {
            // 用户未登录，返回未授权错误
            httpResponse.setContentType("application/json;charset=UTF-8");
            JSONUtil.printByJSON(httpResponse, Result.error("用户未登录，请先登录"));
        }
    }
    
    @Override
    public void destroy() {
        // 过滤器销毁
    }
    
    /**
     * 判断当前请求路径是否在排除列表中
     *
     * @param requestPath 请求路径
     * @return 是否在排除列表中
     */
    private boolean isExcludedPath(String requestPath) {
        for (String excludedPath : excludedPaths) {
            if (requestPath.equals(excludedPath)) {
                return true;
            }
        }
        return false;
    }
} 